package com.blog.service.impl;

import com.blog.exception.ExceptionEnum;
import com.blog.exception.MyException;
import com.blog.mapper.UserMapper;
import com.blog.pojo.PageBean;
import com.blog.pojo.ResultResponse;
import com.blog.pojo.User;
import com.blog.pojo.UserInfoVO;
import com.blog.service.UserService;
import com.blog.utils.AliOSSUtils;
import com.blog.utils.UserContext;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AliOSSUtils aliOSSUtils;

    @Override
    public ResultResponse register(User user) {
        // 校验邮箱、用户名、密码是否为空
        if (user.getEmail() == null || user.getEmail().isEmpty()) {
            throw new MyException(ExceptionEnum.EMPTY_EMAIL);
        }

        if (user.getUsername() == null || user.getUsername().isEmpty()) {
            throw new MyException(ExceptionEnum.EMPTY_USERNAME);
        }

        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            throw new MyException(ExceptionEnum.EMPTY_PASSWORD);
        }

        // 检查邮箱是否已经存在
        if (userMapper.countByEmail(user.getEmail()) > 0) {
            throw new MyException(ExceptionEnum.DUPLICATE_EMAIL);
        }

        // 检查用户名是否已经存在
        if (userMapper.countByUsername(user.getUsername()) > 0) {
            throw new MyException(ExceptionEnum.DUPLICATE_USERNAME);
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 设置注册时间、默认头像和有效位
        user.setCreated(LocalDate.now());
        user.setImage("https://blog240702.oss-cn-hangzhou.aliyuncs.com/35fd3225-a510-4dd2-9506-11dc0b4138f5.png");
        user.setValid(1);

        // 插入用户数据
        userMapper.insertUser(user);

        return ResultResponse.success();
    }

    @Override
    public UserInfoVO login(User user) {
        if(user.getEmail() == null || user.getEmail() == ""){
            throw new MyException(ExceptionEnum.EMPTY_EMAIL);
        }
        if(user.getPassword() == null || user.getPassword() == ""){
            throw new MyException(ExceptionEnum.EMPTY_PASSWORD);
        }
        //调用Mapper层功能获取数据库中加密的用户密码和其他信息
        UserInfoVO loginUser = userMapper.getByEmail(user);
        if (loginUser != null && passwordEncoder.matches(user.getPassword(), loginUser.getPassword())) {
            // 密码匹配，设置身份，返回用户信息
            String identity = userMapper.getIdentity(loginUser.getId());
            if(identity == null){
                identity = "普通用户";
            }
            loginUser.setIdentity(identity);
            return loginUser;
        }
        //密码不匹配或邮箱未注册
        return null;
    }

    //查看自己的信息
    @Override
    public UserInfoVO getCurrentUser() {
        int id = Integer.parseInt(UserContext.getUserId());
        UserInfoVO userInfo = userMapper.getCurrentUser(id);
        userInfo.setFocus(userMapper.getFocus(id));
        userInfo.setFollow(userMapper.getFollower(id));
        String identity = userMapper.getIdentity(id);
        if(identity == null){
            identity = "普通用户";
        }
        userInfo.setIdentity(identity);
        return userInfo;
    }

    @Override
    public UserInfoVO getUserById(Integer id) {
        UserInfoVO userInfo = userMapper.getUserById(id);
        userInfo.setFocus(userMapper.getFocus(id));
        userInfo.setFollow(userMapper.getFollower(id));
        return userInfo;
    }

    @Override
    public void freezeUser(Integer id) {
        userMapper.freezeUser(id);
    }

    @Override
    public void revertUser(Integer id) {
        userMapper.revertUser(id);
    }

    @Override
    public String updateUser(String username, MultipartFile image) throws IOException {
        String img = null;
        int id = Integer.parseInt(UserContext.getUserId());
        if(image != null && !image.isEmpty()) {
            img = aliOSSUtils.upload(image);
            userMapper.updateUser(username, img, id);
            return img;
        }else{
            if (userMapper.countByUsername(username) > 0){
                throw new MyException(ExceptionEnum.DUPLICATE_USERNAME);
            }
                userMapper.updateUser(username, img, id);
            return null;
        }
    }

    @Override
    public ResultResponse updatePassword(String oldPassword, String newPassword) {
        int id = Integer.parseInt(UserContext.getUserId());
        UserInfoVO userInfo = userMapper.getCurrentUser(id);
        if (passwordEncoder.matches(oldPassword, userInfo.getPassword())) {
            // 密码匹配
            newPassword = passwordEncoder.encode(newPassword);
            userMapper.updatePassword(id, newPassword);
            return ResultResponse.success();
        }
        throw new MyException(ExceptionEnum.ERROR_OLDPASSWORD);
    }

    @Override
    public PageBean listUsers(Integer page, Integer pageSize) {
        // 设置分页参数
        PageHelper.startPage(page, pageSize);
        // 执行分页查询
        List<User> userList = userMapper.listUsers();
        // 获取分页结果
        Page<User> p = (Page<User>) (userList);
        // 封装PageBean
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        return pageBean;
    }

    @Override
    public PageBean listUsersByCondition(Integer page, Integer pageSize, String condition) {
        // 设置分页参数
        PageHelper.startPage(page, pageSize);
        // 执行分页查询
        List<User> userList = userMapper.listUsersByCondition(condition);
        // 获取分页结果
        Page<User> p = (Page<User>) (userList);
        // 封装PageBean
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        return pageBean;
    }

    @Override
    public void changePassword(String email, String newPassword) {
        newPassword = passwordEncoder.encode(newPassword);
        if (userMapper.countByEmail(email) == 0) {
            throw new MyException(ExceptionEnum.NOT_REGISTER);
        }
        userMapper.changePassword(email, newPassword);
    }

}
